import type { LockInfo } from '/#/store';
import { defineStore } from 'pinia';
import { lock_info_key } from '/@/common/constant/cacheConst';
import { createLocalStorage } from '/@/common/util/localCache';

const cls = createLocalStorage();

interface LockState {
  lockInfo: Nullable<LockInfo>;
}

export const useLockStore = defineStore({
  id: 'app-lock',
  state: (): LockState => ({
    lockInfo: cls.get(lock_info_key),
  }),
  getters: {
    getLockInfo(): Nullable<LockInfo> {
      return this.lockInfo;
    },
  },
  actions: {
    setLockInfo(info: LockInfo) {
      this.lockInfo = Object.assign({}, this.lockInfo, info);
      cls.set(lock_info_key, this.lockInfo);
    },
    resetLockInfo() {
      cls.remove(lock_info_key);
      this.lockInfo = null;
    },
    // Unlock
    async unLock(password?: string) {
      if (this.lockInfo?.pwd === password) {
        this.resetLockInfo();
        return true;
      }
    },
  },
});
